from PyQt5.QtWidgets import QLineEdit

__author__ = 'sdjkx'

from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import signal


class AutoCompleteEdit(QLineEdit):
    def __init__(self, model, separator=' ', addSpaceAfterCompleting=True):
        super(AutoCompleteEdit, self).__init__()
        self._separator = separator
        self._addSpaceAfterCompleting = addSpaceAfterCompleting
        self._completer = QCompleter(model)
        self._completer.setWidget(self)
        self.connect(
            self._completer,
            signal.signal('activated(QString)'),
            self._insertCompletion)
        self._keysToIgnore = [Qt.Key_Enter,
                              Qt.Key_Return,
                              Qt.Key_Escape,
                              Qt.Key_Tab]

    def _insertCompletion(self, completion):

        extra = len(completion) - len(self._completer.completionPrefix())
        extra_text = completion[-extra:]
        if self._addSpaceAfterCompleting:
            extra_text += ', '
        self.setText(self.text() + extra_text)

    def textUnderCursor(self):
        text = self.text()
        textUnderCursor = ''
        i = self.cursorPosition() - 1
        while i >= 0 and text[i] != self._separator:
            textUnderCursor = text[i] + textUnderCursor
            i -= 1
        return textUnderCursor

    def keyPressEvent(self, event):
        if self._completer.popup().isVisible():
            if event.key() in self._keysToIgnore:
                event.ignore()
                return
        super(AutoCompleteEdit, self).keyPressEvent(event)
        completionPrefix = self.textUnderCursor()
        if completionPrefix != self._completer.completionPrefix():
            self._updateCompleterPopupItems(completionPrefix)
        if len(event.text()) > 0 and len(completionPrefix) > 0:
            self._completer.complete()
        if len(completionPrefix) == 0:
            self._completer.popup().hide()

    def _updateCompleterPopupItems(self, completionPrefix):

        self._completer.setCompletionPrefix(completionPrefix)
        self._completer.popup().setCurrentIndex(
            self._completer.completionModel().index(0, 0))


# if __name__ == '__main__':
#     def demo():
#         import sys
#         app = QtGui.QApplication(sys.argv)
#         values = ['book', 'good', 'perfect', 'lousy', 'messy']
#         editor = AutoCompleteEdit(values)
#         window = QtGui.QWidget()
#         hbox = QtGui.QHBoxLayout()
#         hbox.addWidget(editor)
#         window.setLayout(hbox)
#         window.show()
#
#         sys.exit(app.exec_())
#
#     demo()
